﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace VSSTQH.DataAccess
{
    public class VendorDAO : BaseDataAccess, IVendorDAO
    {

        #region Properties

        private VendorModel _searchObject;
        /// <summary>
        /// Search Object Property
        /// </summary>
        public VendorModel SearchObject
        {
            get { return _searchObject; }
            set
            {
                if (_searchObject != value)
                {
                    _searchObject = value;
                }
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Search Method
        /// </summary>
        /// <returns></returns>
        public IList<VendorModel> Search()
        {
            IList<VendorModel> collection;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                IQueryable<Vendor> query = dataContext.Vendors;
                if (!String.IsNullOrEmpty(_searchObject.VendorID))
                {
                    query = query.Where(e => e.VendorID.Contains(_searchObject.VendorID));
                }
                if (!String.IsNullOrEmpty(_searchObject.VendorName))
                {
                    query = query.Where(e => e.VendorName.Contains(_searchObject.VendorName));
                }
                if (!String.IsNullOrEmpty(_searchObject.Telephone))
                {
                    query = query.Where(e => e.Telephone.Contains(_searchObject.Telephone));
                }
                if (!String.IsNullOrEmpty(_searchObject.Address))
                {
                    query = query.Where(e => e.Address.Contains(_searchObject.Address));
                }
                if (!String.IsNullOrEmpty(_searchObject.Fax))
                {
                    query = query.Where(e => e.Fax.Contains(_searchObject.Fax));
                }
                if (!String.IsNullOrEmpty(_searchObject.TaxID))
                {
                    query = query.Where(e => e.TaxID.Contains(_searchObject.TaxID));
                }
                collection = new List<VendorModel>();
                foreach (var item in query)
                {
                    collection.Add(VendorMapper.ToModel(item));
                }
            }

            return collection;
        }

        /// <summary>
        /// Get all Method
        /// </summary>
        /// <returns></returns>
        public IList<VendorModel> GetAll()
        {
            IList<VendorModel> collection;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                IQueryable<Vendor> query = dataContext.Vendors;

                collection = new List<VendorModel>();
                foreach (var item in query)
                {
                    collection.Add(VendorMapper.ToModel(item));
                }
            }
            
            return collection;
        }

        /// <summary>
        /// Get Method
        /// </summary>
        /// <returns></returns>
        public VendorModel Get()
        {
            VendorModel item = null;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                Vendor query = dataContext.Vendors.FirstOrDefault();

                if (query != null) item = VendorMapper.ToModel(query);
            }

            return item;
        }

        /// <summary>
        /// Get Last Method
        /// </summary>
        /// <returns></returns>
        public VendorModel GetLast()
        {
            VendorModel item = null;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                Vendor query = dataContext.Vendors.LastOrDefault();

                if (query != null) item = VendorMapper.ToModel(query);
            }

            return item;
        }

        /// <summary>
        /// Generate Auto ID Method
        /// </summary>
        /// <param name="dataContext"></param>
        /// <returns></returns>
        private string GenerateAutoID(VssTqhDataContext dataContext)
        {
            string id = String.Empty;
            int length = 10; // length default
            string prefix = String.Empty;
            string startNumber = "1";
            string defaultID = String.Empty;

            // Create Default Key
            Config config = dataContext.Configs.FirstOrDefault();
            if (config != null)
            {
                prefix = config.VendorPrefix;
                length = config.VendorCodeLength;
            }
            defaultID = prefix + startNumber.PadLeft(length, '0');

            // Create Automation Key
            var query = dataContext.Vendors.Where(e =>
                e.VendorID.StartsWith(prefix));
            if (query != null)
                id = query.Max(e => e.VendorID);

            if (String.IsNullOrEmpty(id))
                id = defaultID;
            else
            {
                id = id.Remove(0, prefix.Length);
                int numberID;
                string suffix;
                if (Int32.TryParse(id, out numberID))
                {
                    numberID++;
                    suffix = numberID.ToString().PadLeft(length, '0');
                    id = prefix + suffix;
                }
                else
                {
                    id = defaultID;
                }
            }
            return id;
        }

        /// <summary>
        /// Add Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Add(VendorModel item)
        {
            bool result = false;
            try
            {
                using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
                {
                    if (String.IsNullOrEmpty(item.VendorID))
                    {
                        item.VendorID = GenerateAutoID(dataContext);
                    }

                    Vendor entity = new Vendor();
                    VendorMapper.ToEntity(entity, item);
                    dataContext.Vendors.InsertOnSubmit(entity);
                    dataContext.SubmitChanges();

                    result = true;
                    item.IsNew = false;
                    item.IsEdit = false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return result;
        }

        public bool Add(IList<VendorModel> collection)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Edit Item Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Edit(VendorModel item)
        {
            bool result = false;
            try
            {
                using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
                {
                    Vendor entity = dataContext.Vendors.Where(e => e.VendorID == item.VendorID).SingleOrDefault();
                    if (entity != null)
                    {
                        VendorMapper.ToEntity(entity, item);
                        dataContext.SubmitChanges();
                        result = true;
                        item.IsNew = false;
                        item.IsEdit = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// Edit collection Method
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public bool Edit(IList<VendorModel> collection)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Delete Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Delete(VendorModel item)
        {
            bool result = false;
            try
            {
                using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
                {
                    Vendor entity = dataContext.Vendors.Where(e => e.VendorID == item.VendorID).SingleOrDefault();
                    if (entity != null)
                    {
                        dataContext.Vendors.DeleteOnSubmit(entity);
                        dataContext.SubmitChanges();
                        result = true;
                    }
                }
                
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return result;
        }

        public bool Delete(IList<VendorModel> collection)
        {
            throw new NotImplementedException();
        }

        #endregion


        #region IBaseDataAccess<VendorModel> Members


        public IList<VendorModel> GetAllActive()
        {
            throw new NotImplementedException();
        }

        public bool Add(IList<VendorModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        public bool Edit(IList<VendorModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        public bool Save(IList<VendorModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        public bool Delete(IList<VendorModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
